package baidu.bms.filter;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

;import static baidu.bms.filter.DubboContext.transparentHeaders;

/**
 * @author sunqiyuan
 * @Classname Filter
 * @Description servlet的过滤器 ，可以拦截请求
 * @Date 2020/10/16 2:44 下午
 * @Version V1.0
 */
public class HttpFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(HttpFilter.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // do nothing
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 拦截客户请求中关于
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
            HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

            Map<String, String> context = DubboContext.getContextMap();

            if (context == null) {
                // 作为server接收时
                context = new HashMap<>();
                for (String header : transparentHeaders) {
                    // header 形如 traceId: a1;a2;a3，此处只返回a1
                    String value = httpRequest.getHeader(header);
                    if (value != null) {
                        context.put(header, value);
                    }
                }
                DubboContext.setContextMap(context);
                System.out.println("http in server!" + getHeaders(httpRequest));
            } else {
                for (Map.Entry<String, String> element : context.entrySet()) {
                    httpResponse.addHeader(element.getKey(), element.getValue());
                }
                System.out.println("http in client!" + getHeaders(httpRequest));
                DubboContext.setContextMap(null);

            }
        } catch (Exception e) {
            logger.warn("Exception in HttpFilter {}", e);
        }
        // 执行用户请求
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {
        // do nothing
    }

    public Map<String, String> getHeaders(HttpServletRequest httpRequest) {
        Enumeration<String> headerNames = httpRequest.getHeaderNames();
        Map<String, String> headers = new HashMap<>();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String key = headerNames.nextElement();
                headers.put(key, httpRequest.getHeader(key));
            }
        }
        return headers;
    }
}
